//
//  AppDelegate.swift
//  NewXueBa
//
//  Created by Shine on 2019/5/30.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    lazy var reachability: NetworkReachabilityManager? = {
        return NetworkReachabilityManager(host: "https://www.baidu.com")
    }()
    
    var window: UIWindow?
    var centralManager: CBCentralManager?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        loadBCApplication() //加载应用
        configReachability() //网络监控
        centralManager = CBCentralManager(delegate: self, queue: nil) //蓝牙监控
        return true
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        BCUserManager.shareManager.Reachability_isNet.value = true
        print("有网络")
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

extension AppDelegate: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            print("蓝牙打开")
            BCUserManager.shareManager.BlueTooth_isOpen.value = true
        } else {
            print("蓝牙不可用")
            Gloab_Connect_Device = nil //清除连接的设备
            RobotPenManager.share()?.disconnectDevice()//断开设备
            BCUserManager.shareManager.BlueTooth_isOpen.value = false
        }
    }
}

extension AppDelegate {
    // z加载应用
    fileprivate func loadBCApplication() {
        if BCUserManager.shareManager.isLogin! {
            self.window?.rootViewController = BCBaseTabBarVC.rootTabbarClass()
            DispatchQueue.global().async {
                //耗时操作
                WebSocketManager.sharedInstance().loginWebSocketBaseUrl(XueBa_WebSocketURL, port: XueBa_WebSocketPort, userUid: BCUserManager.shareManager.user_uid ?? "", userToken: BCUserManager.shareManager.user_token ?? "")
            }
        } else {
            self.window?.rootViewController = UIStoryboard.viewController(from: .LoginSB, viewControllerClass: StudyLoginVC.self)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(notiCenterForceLogout), name: NSNotification.Name(rawValue: "testForceLogout_Noti"), object: nil)
    }
    //其他地方登陆了 强制退出
    @objc fileprivate func notiCenterForceLogout() {
        DispatchQueue.main.async {
            if BCUserManager.shareManager.isLogin! {
                // 如果是登录状态说明是被挤出了
                self.window?.rootViewController = UIStoryboard.viewController(from: .LoginSB, viewControllerClass: StudyLoginVC.self)
                BCBaseVC.showTipMsgInWindow("账号在其他地方登录", time: 1)
            }
        }
    }
    
    private func configReachability() {
        reachability?.listener = { status in
            switch status {
            case .reachable(.ethernetOrWiFi), .reachable(.wwan):
                BCUserManager.shareManager.Reachability_isNet.value = true
                print("有网络")
            default:
                BCUserManager.shareManager.Reachability_isNet.value = false
                print("无网络")
            }
        }
        reachability?.startListening()
    }
    
    
}
